<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">AI 智能客服</text>
      <view class="status" :class="{ 'status-active': isSessionActive }">
        {{ isSessionActive ? '会话已连接' : '未连接' }}
      </view>
    </view>

    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true" 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
      ref="chatScrollView"
    >
      <block v-if="messages.length === 0">
        <view class="welcome-container">
          <image class="welcome-logo" src="/static/ai-robot.png" mode="aspectFit"></image>
          <text class="welcome-text">欢迎使用AI智能客服</text>
          <text class="welcome-subtext">请点击下方"开始对话"按钮初始化会话</text>
        </view>
      </block>
      <block v-else>
        <view 
          v-for="(msg, index) in messages" 
          :key="index" 
          class="message-wrapper"
          :class="{ 'user-message-wrapper': msg.role === 'user', 'ai-message-wrapper': msg.role === 'ai' }"
        >
          <!-- AI头像保持在左侧 -->
          <view class="avatar" v-if="msg.role === 'ai'">
            <image :src="baseUrl + 'ai_p.png'" mode="aspectFill"></image>
          </view>
          
          <view 
            class="message" 
            :class="{ 'user-message': msg.role === 'user', 'ai-message': msg.role === 'ai' }"
          >
            <text class="message-text">{{ msg.content }}</text>
            <text class="message-time">{{ formatTime(msg.timestamp) }}</text>
          </view>
          
          <!-- 用户头像放在右侧 -->
          <view class="avatar" v-if="msg.role === 'user'">
            <image :src="userPic" mode="aspectFill"></image>
          </view>
        </view>
      </block>
      <!-- 加载状态 -->
      <view class="loading-wrapper" v-if="isLoading">
        <view class="loading-dots">
          <view class="dot"></view>
          <view class="dot"></view>
          <view class="dot"></view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <button 
        v-if="!isSessionActive" 
        class="init-button" 
        @click="initSession"
        :disabled="isLoading"
      >开始对话</button>
      <block v-else>
        <textarea
          class="input-field"
          v-model="inputMessage"
          placeholder="请输入您的问题..."
          :disabled="isLoading"
          :focus="inputFocus"
          @confirm="sendMessage"
          auto-height
          @input="adjustTextareaHeight"
          ref="messageInput"
        ></textarea>
        <button 
          class="send-button" 
          @click="sendMessage" 
          :disabled="!inputMessage.trim() || isLoading"
        >发送</button>
      </block>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import axios from "axios";

// 响应式状态
const isSessionActive = ref(false);
const isLoading = ref(false);
const inputMessage = ref('');
const inputFocus = ref(false);
const scrollTop = ref(0);
const messages = ref([]);
const openId = ref(''); // 用户标识

let baseUrl = uni.$baseUrl

let userPic = ref("");

// 页面加载
onMounted(() => {
  // 从本地存储获取用户ID
  let userInfo = uni.getStorageSync('userInfo');
  userPic.value = baseUrl + userInfo.user_picture
  const storedOpenId = userInfo.user_id;
  if (storedOpenId) {
    openId.value = storedOpenId;
  }
  
  // 检查是否已有活跃会话
  // const sessionActive = uni.getStorageSync('session_active');
  // if (sessionActive && openId.value) {
  //   isSessionActive.value = true;
  //   loadCachedMessages();
  //   nextTick(() => {
  //     scrollToBottom();
  //   });
  // }
});

// 获取缓存的聊天记录
const loadCachedMessages = () => {
  try {
    const cachedMessages = uni.getStorageSync(`chat_messages_${openId.value}`);
    if (cachedMessages) {
      messages.value = JSON.parse(cachedMessages);
      nextTick(() => {
        scrollToBottom();
      });
    }
  } catch (e) {
    console.error('读取缓存聊天记录失败', e);
  }
};

// 保存聊天记录到本地存储
const saveChatMessages = () => {
  try {
    // 避免存储过多消息，只保留最近50条
    const messagesToSave = messages.value.slice(-50);
    uni.setStorageSync(`chat_messages_${openId.value}`, JSON.stringify(messagesToSave));
  } catch (e) {
    console.error('保存聊天记录失败', e);
  }
};

// 生成随机用户ID (如果没有登录系统)
const generateOpenId = () => {
  // 实际项目中应从登录系统获取用户ID
  return 'user_' + Math.random().toString(36).substr(2, 9);
};

// 初始化会话
const initSession = async () => {
  try {
    isLoading.value = true;
    
    // 如果没有openId，生成一个
    if (!openId.value) {
      openId.value = generateOpenId();
      uni.setStorageSync('user_open_id', openId.value);
    }
	
	// 执行初始化
	const response = await axios.get(`https://php.meibug.cn/japi/ai/start/${openId.value}`);
    
    if (response.status === 200 && response.data.code == 1) {
      isSessionActive.value = true;
      uni.setStorageSync('session_active', true);
      
      // 加载缓存的聊天记录
      loadCachedMessages();
      
      // 如果没有历史消息，添加欢迎消息
      if (messages.value.length === 0) {
        const welcomeMsg = {
          role: 'ai',
          content: '嘿，牢弟！有什么事，说。',
          timestamp: Date.now()
        };
        messages.value.push(welcomeMsg);
        saveChatMessages();
      }
      
      nextTick(() => {
        scrollToBottom();
        inputFocus.value = true;
      });
    } else {
      uni.showToast({
        title: '初始化会话失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('初始化会话错误', error);
    uni.showToast({
      title: '网络错误，正在重试重新连接...',
      icon: 'none'
    });
	initSession();
  } finally {
    isLoading.value = false;
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;
  
  const userMsg = {
    role: 'user',
    content: inputMessage.value.trim(),
    timestamp: Date.now()
  };
  
  messages.value.push(userMsg);
  saveChatMessages();
  
  const tempInputMessage = inputMessage.value;
  inputMessage.value = '';
  
  nextTick(() => {
    scrollToBottom();
  });
  
  try {
    isLoading.value = true;
	
	let tempParamt = {
		openId: openId.value,
		question: tempInputMessage
	}
	
	const response = await axios.post("https://php.meibug.cn/japi/ai/send", tempParamt)
    
	// console.log(response);
	
    if (response.status === 200) {
      const aiMsg = {
        role: 'ai',
        content: response.data,
        timestamp: Date.now()
      };
      
      messages.value.push(aiMsg);
      saveChatMessages();
      
      nextTick(() => {
        scrollToBottom();
      });
    } else {
      uni.showToast({
        title: '获取回复失败',
        icon: 'none'
      });
      
      // 添加错误消息
      const errorMsg = {
        role: 'ai',
        content: '抱歉，我暂时无法回答您的问题，请稍后再试。',
        timestamp: Date.now()
      };
      
      messages.value.push(errorMsg);
      saveChatMessages();
    }
  } catch (error) {
    console.error('发送消息错误', error);
    
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
    
    // 添加错误消息
    const errorMsg = {
      role: 'ai',
      content: '网络连接错误，请检查您的网络后重试。',
      timestamp: Date.now()
    };
    
    messages.value.push(errorMsg);
    saveChatMessages();
  } finally {
    isLoading.value = false;
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery().in(this);
    query.select('.chat-messages').boundingClientRect();
    query.exec((res) => {
      if (res && res[0]) {
        scrollTop.value = res[0].height * 1000; // 确保足够大的值使其滚动到底部
      }
    });
  });
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 加载更多历史消息
const loadMoreMessages = () => {
  // 此处可以实现加载更多历史消息的逻辑
  // 如果需要从服务器获取更多历史消息，可以在这里实现
};

// 调整输入框高度
const adjustTextareaHeight = () => {
  // 根据内容长度自动调整输入框高度
};


// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
});
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  /* height: 98vh; */
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #1989fa;
  color: #ffffff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.status {
  font-size: 24rpx;
  background-color: #ff4d4f;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}

.status-active {
  background-color: #52c41a;
}

.welcome-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
}

.welcome-logo {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.welcome-text {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.welcome-subtext {
  font-size: 28rpx;
  color: #666;
}

.chat-messages {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  padding-bottom: 85px;
  font-size: 15px;
}

.message-wrapper {
  display: flex;
  margin-bottom: 60rpx;
}

.user-message-wrapper {
  justify-content: flex-end;
}

.ai-message-wrapper {
  justify-content: flex-start;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  background-color: #e0e0e0;
}

.avatar image {
  width: 100%;
  height: 100%;
}

.message {
  max-width: 70%;
  border-radius: 20rpx;
  padding: 20rpx;
  position: relative;
  margin: 0 20rpx;
}

.user-message {
  background-color: #1989fa;
  color: #ffffff;
  border-top-left-radius: 20rpx;  /* 修改这里 */
  border-top-right-radius: 0;     /* 气泡尖角在右侧 */
  border-bottom-left-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
}

.ai-message {
  background-color: #ffffff;
  color: #333333;
  border-top-left-radius: 0;      /* 气泡尖角在左侧 */
  border-top-right-radius: 20rpx; /* 修改这里 */
  border-bottom-left-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.message-text {
  font-size: 32rpx;
  line-height: 1.5;
  word-break: break-word;
}

.message-time {
  font-size: 22rpx;
  color: #999;
  position: absolute;
  bottom: -30rpx;
  right: 10rpx;
}

.user-message .message-time {
  color: #ccc;
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  margin: 20rpx 0;
}

.loading-dots {
  display: flex;
}

.dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #999;
  margin: 0 6rpx;
  animation: dot-flashing 1s infinite alternate;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes dot-flashing {
  0% {
    opacity: 0.2;
  }
  100% {
    opacity: 1;
  }
}

.input-area {
	padding: 20rpx;
	background-color: #fff;
	border-top: 2rpx solid #eee;
	display: flex;
	align-items: center;
	position: fixed;
	bottom: 0px;
	width: 100vw;
	box-sizing: border-box;
}

.init-button {
  width: 100%;
  background-color: #1989fa;
  color: #ffffff;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 45rpx;
}

.input-field {
  flex: 1;
  background-color: #f8f8f8;
  border-radius: 36rpx;
  padding: 20rpx 30rpx;
  font-size: 32rpx;
  min-height: 80rpx;
  max-height: 200rpx;
}

.send-button {
  margin-left: 20rpx;
  background-color: #1989fa;
  color: #ffffff;
  width: 160rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 32rpx;
}

button[disabled] {
  opacity: 0.6;
}

.user-message-wrapper {
  justify-content: flex-end;
  flex-direction: row; /* 确保为行方向 */
  padding-right: 20px;
}

.ai-message-wrapper {
  justify-content: flex-start;
  flex-direction: row; /* 确保为行方向 */
}
</style>